<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/11/6
 * Time: 下午6:07
 */

namespace common\helpers;


class FuncHelper
{
    const CAPACITY_UNIT_B = 'B';
    const CAPACITY_UNIT_K = 'K';
    const CAPACITY_UNIT_M = 'M';
    
    public static function formatCapacitySize($size, $unit = null, $format = true) {
        $bitSize = 1024;
        $formatUnit = '';
        $formatSize = 0;
        $size = floatval($size);
        switch ($unit) {
            case self::CAPACITY_UNIT_B:
                $formatUnit = $unit;
                $formatSize = $size;
                break;
            case self::CAPACITY_UNIT_K:
                $formatUnit = $unit;
                $formatSize = sprintf('%.1f', (float)$size/$bitSize);
                break;
            case self::CAPACITY_UNIT_M:
                $formatUnit = $unit;
                $formatSize = sprintf('%.1f', (float)$size/($bitSize*$bitSize));
                break;
            default:
                if($size < $bitSize) {
                    $formatUnit = 'B';
                    $formatSize = $size;
                }else if($size < $bitSize*$bitSize){
                    $formatUnit = 'K';
                    $formatSize = sprintf('%.1f', (float)$size/$bitSize);
                }else {
                    $formatUnit = 'M';
                    $formatSize = sprintf('%.1f', (float)$size/($bitSize*$bitSize));
                }
                break;
        }
        if($format) {
            return $formatSize . ' ' . $formatUnit;
        }else {
            return floatval($formatSize);
        }
    }
}